const express = require("express")

const app = express()

// 应用级别中间件
app.use(express.json())


let todoList = [
  {
    id: 1,
    name: "kerwin",
    age: 100
  },
  {
    id: 2,
    name: "david",
    age: 100
  },
  {
    id: 3,
    name: "lingling",
    age: 100
  }
]

// 获取列表
app.get("/list",(req, res) => {
  res.send(todoList)
})

// 根据id 删除
app.delete("/del",(req, res) => {
  const {id} = req.query
  todoList = todoList.filter(item => item.id !== Number(id))
  res.send(todoList)

})
// 创建
app.post("/create",(req,res) => {
  const {name, age} = req.body
  todoList.push({
    id: todoList.length + 1,
    name: name,
    age: age
  })
  res.send(todoList)

})
// 通过id修改
app.put("/update", async (req, res) => {
  const {id, name, age} = req.body
  todoList = todoList.map(item => {
    return {
      id: item.id === id ? id : item.id,
      name: item.id === id ? name : item.name,
      age: item.id === id ? age : item.age,
    }
  })
  try {
    const {code, data} = await updateApi()
    if (code === 200) {

    }
  } catch (e) {

  }
 updateApi().then(res => {
   if(res.code === 200) {

   }
 }).catch().finally()



  res.send(todoList)
})

// 创建
app.post("/api/aaa",(req,res) => {

  console.log(req.body)
  res.send("hello world")

})
app.listen(3000, ()=> {
  console.log("sever start")
})